#include "librarymodel.h"
#include "qedalibrary.h"

#include <QtCore/qfileinfo.h>

LibraryModel::LibraryModel(QObject *parent) :
    QObject(parent)
{
}

LibraryModel::~LibraryModel()
{
    qDeleteAll(m_libraries);
}

bool LibraryModel::containsLibrary(const QString &filePath)
{
    for (int i = 0; i < m_libraries.count(); ++i)
        if (m_libraries.at(i)->path().compare(filePath.simplified(), Qt::CaseInsensitive) == 0)
            return true;
    return false;
}

QedaLibrary *LibraryModel::createLibrary(const QString &libName, const QString &filePath)
{
    QedaLibrary *newLib = newLibrary();
    newLib->setPath(filePath);
    newLib->setName(libName);
    m_libraries.append(newLib);
    emit libraryAdded(newLib);
    newLib->setModified(true);
    return newLib;
}

void LibraryModel::deleteLibrary(QedaLibrary *lib)
{
    disconnect(lib, SIGNAL(componentsAdded(QedaLibrary*,QList<QedaComponent*>)),
               this, SIGNAL(componentsAdded(QedaLibrary*,QList<QedaComponent*>)));
    disconnect(lib, SIGNAL(componentUpdated(QedaComponent*)),
               this, SIGNAL(componentUpdated(QedaComponent*)));
    disconnect(lib, SIGNAL(componentRemoved(QedaComponent*)),
               this, SIGNAL(componentRemoved(QedaComponent*)));
    delete  lib;
}

QedaLibrary *LibraryModel::loadLibrary(const QString &filePath)
{
    QedaLibrary *lib = 0;
    for (int i = 0; i < m_libraries.count(); ++i)
        if (m_libraries.at(i)->path().compare(filePath.simplified(), Qt::CaseInsensitive) == 0)
            lib = m_libraries.at(i);
    if (!lib)
    {
        lib = newLibrary();
        if (lib->load(filePath))
        {
            m_libraries.append(lib);
            emit libraryAdded(lib);
            if (lib->components().count())
                emit componentsAdded(lib, lib->components());
        }
        else
        {
            deleteLibrary(lib);
            lib = 0;
        }
    }
    return lib;
}

QedaLibrary *LibraryModel::newLibrary()
{
    QedaLibrary *newLib = new QedaLibrary(this);
    connect(newLib, SIGNAL(componentsAdded(QedaLibrary*,QList<QedaComponent*>)),
            this, SIGNAL(componentsAdded(QedaLibrary*,QList<QedaComponent*>)));
    connect(newLib, SIGNAL(componentUpdated(QedaComponent*)),
            this, SIGNAL(componentUpdated(QedaComponent*)));
    connect(newLib, SIGNAL(componentRemoved(QedaComponent*)),
            this, SIGNAL(componentRemoved(QedaComponent*)));
    return newLib;
}

void LibraryModel::removeLibrary(QedaLibrary *library)
{
    if (m_libraries.removeOne(library))
        emit libraryRemoved(library);
    delete library;
}

